<?php
header("Content-Type: text/html;charset=utf-8");
$stime=microtime(true); 
set_time_limit(0);
global $source_dir;
global $target_dir;
$source_dirs = "source_dirs/";//目标路径

//获取目录下的文件夹名称 Linyufan.com 2021-05-31 17:19:53
function getSubDirs($dir){
    $subdirs = array();
    if(!$dh = opendir($dir)) 
        return $subdirs;
    $i = 0;
    while ($f = readdir($dh)) 
    {
        if($f =='.' || $f =='..') 
            continue;
        //如果只要子目录名, path = $f;
        //$path = $dir.'/'.$f;  
        $path = $f;
        $subdirs[$i] = $path;
        $i++;
    }
    return $subdirs;
}






/**
 * @ Author:      林羽凡 Linyufan.com
 * @ DateTime:    2021-05-31 12:30:24
 * @ 开始扫描文件夹
 * @ $quality:  压缩图片质量 从0--100 依次增大
 * @ $img_size：大于这个宽度的图片就裁剪
 * @ $file_byte：大于这个体积的图片就压缩
 */
$img_size = 4100; //最大宽度
$file_byte = 638940; //600Kb的大小


//exit('finish');



foreach (getSubDirs($source_dirs) as $k => $v){
    $source_dir = $source_dirs.$v.'/';
    $target_dir = $source_dirs.$v.'/';//最终路径
    scan_dir($source_dir,$file_byte,$img_size);
}




//scan_dir($source_dir,$file_byte,$img_size);


function log_msg($msg){
    echo "$msg\r\n";
}



/**
 * 压缩图片文件
 * @param $path_file
 * @return array
 * Linyufan.com 2021-05-31 12:28:09
 */
function linyufan_compress_img($path_file,$file_byte,$img_size){
    $path_file = rtrim($path_file,'/');
    if (!is_file($path_file)) return array('msg'=>'图片不存在','status'=>false);

    global $source_dir;
    global $target_dir;

    $file_ext = substr(strrchr($path_file, '.'), 1); //直接获取文件后缀名 Linyufan.com 2021-05-31 11:30:07
    if($file_ext == 'mp4'){
        return array('msg'=>'fail','status'=>false); //如果是视频文件就直接退出
    }

    $file_name = substr($path_file,strrpos($path_file,'/')+1);
    $dir = substr($path_file,0,strrpos($path_file,'/')+1);
    $imginfo = getimagesize($path_file);
    $ext = strtolower(substr(end($imginfo),strrpos(end($imginfo),'/')+1));
    //list($width, $height, $type, $attr) = getimagesize($path_file);
    //print_r($imginfo);exit;

    $new_width = $imginfo[0];//压缩后的图片宽
    $new_height = $imginfo[1];//压缩后的图片高

    $width = $imginfo[0];//原图片宽
    $height = $imginfo[1];//原图片高

    if($width >= $img_size){
        $per = $img_size / $width;//计算比例
        $new_width = $width * $per;
        $new_height = $height * $per;
    }
    $file_size = filesize($path_file); //获取文件大小
    if($file_size<$file_byte){
        return array('msg'=>'fail','status'=>false); //比指定文件小的就不压缩了
    }

    //按文件大小，划分不同的压缩等级 Linyufan.com 2021-05-31 14:55:33
    switch ($file_size) {
        case $file_size > 10500000:
            //大于10M
            $quality = 10;echo '>10M';
            break;

        case $file_size > 6290000:
            //大于6M
            $quality = 13;echo '>6M';
            break;

        case $file_size > 3200000:
            //大于3M
            $quality = 20;echo '>3M';
            break;
        case $file_size > 1200000:
            //大于1M
            $quality = 30;echo '>1M';
            break;
        case $file_size > 638940:
            //大于1M
            echo '>600k';
            $quality = 18;
            break;
        default:
            $quality = 20;
            break;
    }
    
    $new_dir = str_replace($source_dir,$target_dir,$dir);
    if (!is_dir($new_dir)){
        $rs = mkdir($new_dir,0777,true);
        if (!$rs) return array('msg'=>'创建文件夹失败','status'=>false);
    }
    /*新文件名*/
    $new_file_name = substr($file_name,0,strrpos($file_name,'.')).".".$file_ext;
    echo '文件格式：'.$file_ext.'*****';
    $path_new_file = "{$new_dir}{$new_file_name}";
    switch ($ext){
        case "png":
            echo '格式:'.$ext.'<br>';
            $image_wp = imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefrompng($path_file);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            imagejpeg($image_wp,$path_new_file,$quality);
            imagedestroy($image_wp);
            imagedestroy($image);
            break;
        case "gif":
            //$file = imagecreatefromgif($path_file);
            //imagejpeg($file,$path_new_file,$quality);
            //echo '有gif跳过。';
            break;
        case "jpg":
        case "jpeg":
        default:
            $image_wp = imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefromjpeg($path_file);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            imagejpeg($image_wp,$path_new_file,$quality);
            imagedestroy($image_wp);
            imagedestroy($image);
            break;
    }
    return array('msg'=>'success','status'=>true);    
}


/**
 * 扫描文件夹
 * @param $path_dir
 */
function scan_dir($path_dir,$file_byte,$img_size){
    if (!is_dir($path_dir)) return false;
    $rs = scandir($path_dir);
    foreach ($rs as $k => $v){
        if ($v === '.' || $v === '..') continue;
        $path = $path_dir.rtrim($v,'/');
        if (is_file($path)){
            $rs = linyufan_compress_img($path,$file_byte,$img_size);
            if ($rs['status']){
                $rs = "finish";
            }else{
                $rs = $rs['msg'];
                log_msg("太小跳过<br>");
            }
            log_msg("{$path}---{$rs}<br>");
            continue;
            header( $header, $replace = TRUE, $http_response_code );
        }
        if (is_dir($path."/")) scan_dir($path."/");
    }
}



$etime=microtime(true);//获取程序执行结束的时间
$total=$etime-$stime;   //计算差值
echo "<br />当前页面执行时间为：{$total} 秒";

?>